package com.jp.knowledge.fragment;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.jiayen.cache.FileCacheManager;
import com.jp.knowledge.R;
import com.jp.knowledge.activity.BaseFragment;
import com.jp.knowledge.activity.ProductDetailActivity;
import com.jp.knowledge.adapter.OnItemListerner;
import com.jp.knowledge.adapter.ProductAdpater;
import com.jp.knowledge.logic.ProductFragmentLogic;
import com.jp.knowledge.model.ProdcutData;
import com.jp.knowledge.refresh.JpRefreshView;
import com.jp.knowledge.view.JpDiver;

import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @author jiayen     2017-06-09 15:54:41
 *
 * 产品fragment
 */
public class ProductFragment extends BaseFragment {

    private View mView;

    @ViewInject(R.id.refresh)
    private CanRefreshLayout  refreshLayout;

    @ViewInject(R.id.can_refresh_footer)
    private JpRefreshView refreshFooter;

    @ViewInject(R.id.can_content_view)
    private RecyclerView  recyclerView;

    @ViewInject(R.id.comm_new_fragment_remind_bg)
    private LinearLayout emptyLayout;


    private ProductFragmentLogic logic;
    private ProductAdpater adpater;
    private int action;
    private List<ProdcutData>  datas;
    private int page =1;
    private boolean fresh;

    private String cachePath;
    private FileCacheManager cacheManager;

    public ProductFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if(mView == null) {
            mView = inflater.inflate(R.layout.fragment_product, container, false);
            x.view().inject(this, mView);
            init();
        }
        return mView;
    }

    @Override
    public void onDestroy() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                cacheManager.wirteObject(datas, cachePath);
            }
        }).start();
        super.onDestroy();
    }

    private void init(){

        action =((Activity)mContext).getIntent().getIntExtra("action",1);

        logic  = ProductFragmentLogic.getIntance(mContext);
        logic.setCallback(new ProductFragmentLogic.SucCallback() {
            @Override
            public void success(List<ProdcutData> list) {
                if(fresh) {
                    datas = list;
                    refreshFooter.setLoadComplete(false);
                }else{
                    if(datas==null)datas=new ArrayList<ProdcutData>();
                    datas.addAll(list);
                    if(list == null || list.size() == 0)
                        refreshFooter.setLoadComplete(true);
                }
                setData();
            }

            @Override
            public void compelete() {
                if(fresh){
                    refreshLayout.refreshComplete();
                }else {
                    refreshLayout.loadMoreComplete();
                }
            }
        });
        cachePath = mContext.getCacheDir() + "/productContentData_" + action + ".dat";
        cacheManager = new FileCacheManager();

        adpater = new ProductAdpater(mContext,datas);
        final LinearLayoutManager manager = new LinearLayoutManager(mContext,LinearLayoutManager.VERTICAL,false);
        recyclerView.setLayoutManager(manager);
        recyclerView.addItemDecoration(new JpDiver(mContext));
        recyclerView.setAdapter(adpater);
//        getData(0);
        if(datas!=null){
            setData();
        }else{
            emptyLayout.setVisibility(View.VISIBLE);
        }


        refreshLayout.setLoadMoreEnabled(true);

        //刷新
        refreshLayout.setOnRefreshListener(new CanRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                fresh =true;
                page=1;
                getData(0);
            }
        });

        //加载更多
        refreshLayout.setOnLoadMoreListener(new CanRefreshLayout.OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                if(!refreshFooter.isLoadComplete()) {
                    fresh = false;
                    page++;
                    getData(1);
                } else{
                    refreshLayout.loadMoreComplete();
                }
            }
        });

        adpater.setOnItemListener(new OnItemListerner() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent(mContext, ProductDetailActivity.class);
                intent.putExtra("id",datas.get(position).getId());
                intent.putExtra("action",action);
                startActivity(intent);
            }
        });

        readCache();
    }

    private void readCache(){
        Observable.create(new Observable.OnSubscribe<List<ProdcutData>>() {
            @Override
            public void call(Subscriber<? super List<ProdcutData>> subscriber) {
                List<ProdcutData> data = (List<ProdcutData>) cacheManager.readObject(cachePath);
                subscriber.onNext(data);
            }
        }).subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Subscriber<List<ProdcutData>>() {
            @Override
            public void onCompleted() {
                if(adpater.getItemCount() > 0){
                    fresh =true;
                    page=1;
                    getData(0);
                } else {
                    refreshLayout.autoRefresh();
                }
            }
            @Override
            public void onError(Throwable e) {
                onCompleted();
            }
            @Override
            public void onNext(List<ProdcutData> data) {
                if(data != null) {
                    datas = data;
                    setData();
                }
                onCompleted();
            }
        });
    }

    /***
     * 获取数据
     */
    private   void getData(int mode){
        logic.getExpList(action,mode,page,System.currentTimeMillis());
    }
    private void setData() {
        if(datas==null){
            emptyLayout.setVisibility(View.VISIBLE);
        }else{
            emptyLayout.setVisibility(View.GONE);
        }
        adpater.updataAdapter(datas);
    }
}
